#!/bin/bash
set -e

curl https://raw.githubusercontent.com/maxiaof/github-hosts/master/hosts >> /etc/hosts

GIT_PROJECT=`basename "${JIANMU_REMOTE_URL}" .git`

if [ -z "${JIANMU_REMOTE_URL}" ]
then
  echo "[ERROR] The necessary git source configuration is missing"
  exit 1
fi

# write in username password
if [ -n "${JIANMU_USERNAME}" ] && [ -n "${JIANMU_PASSWORD}" ]
then
  # check url
  echo ${JIANMU_REMOTE_URL} > url
  URL_FLAG=`cut url -d "@" -f 2`
  if [ ${URL_FLAG} != "${JIANMU_REMOTE_URL}" ]; then
    if [ -n "${JIANMU_SSH_KEY}" ]; then
        echo "[WARN] The URL using username and password is not configured correctly. Try to use the URL configured by SSH_KEY"
    else
        echo "[ERROR] URL Configuration Error"
        exit 1
    fi
  fi

  NETRC_MACHINE=`echo ${JIANMU_REMOTE_URL} | awk -F "//" '{print $2}' | awk -F "/" '{print $1}' | awk -F ":" '{print $1}'`
  echo "machine: ${NETRC_MACHINE}"

  mkdir -p ${HOME}
  	cat <<EOF > ${HOME}/.netrc
  machine ${NETRC_MACHINE}
  login ${JIANMU_USERNAME}
  password ${JIANMU_PASSWORD}
EOF
  chmod 600 ${HOME}/.netrc
else
  echo "[WARN] The username or password configuration is missing,try use ssh"
fi

# write in ssh key
if [ -n "${JIANMU_SSH_KEY}" ]; then
  # check url
   echo ${JIANMU_REMOTE_URL} > url
    URL_FLAG=`cut url -d "@" -f 2`
    if [ ${URL_FLAG} == "${JIANMU_REMOTE_URL}" ]; then
      if [ -n "${JIANMU_USERNAME}" ] && [ -n "${JIANMU_PASSWORD}" ]; then
         echo "[WARN] The URL using the SSH key is not configured correctly. URL trying to configure with username and password"
      else
         echo "[ERROR] URL Configuration Error"
         exit 1
      fi
    fi

	mkdir -p ${HOME}/.ssh
	echo -n "$JIANMU_SSH_KEY" > ${HOME}/.ssh/id_rsa
	chmod 600 ${HOME}/.ssh/id_rsa

  touch ${HOME}/.ssh/known_hosts
	chmod 600 ${HOME}/.ssh/known_hosts

  if [ ${URL_FLAG} != "${JIANMU_REMOTE_URL}" ]; then
      # compatible default port is not 22
        HAS_PORT=`echo ${JIANMU_REMOTE_URL} | awk -F ":" '{print $1}'`
        if [ ${HAS_PORT} == "ssh" ]; then
            NETRC_MACHINE=`echo ${JIANMU_REMOTE_URL} | awk -F "@" '{print $2}' | awk -F "/" '{print $1}'`
            echo ${NETRC_MACHINE} > /tmp/machine
            IP=`cut /tmp/machine -d ":" -f 1`
            PORT=`cut /tmp/machine -d ":" -f 2`
            ssh-keyscan -H -p ${PORT} ${IP} > ${HOME}/.ssh/known_hosts 2> /dev/null
        else
            NETRC_MACHINE=`echo ${JIANMU_REMOTE_URL} | awk -F "@" '{print $2}' | awk -F ":" '{print $1}'`
            ssh-keyscan -H ${NETRC_MACHINE} > ${HOME}/.ssh/known_hosts 2> /dev/null
        fi
  fi
else
  echo "[WARN] The SSH configuration is missing,try use username,password"
fi

cd /usr
mkdir -p ${GIT_PROJECT}
cd ${GIT_PROJECT}

git_init() {
  if [ ! -d ".git" ];then
    git init
    git remote add origin ${JIANMU_REMOTE_URL}
  fi
}

change_project_dir() {
  cd /usr
  mkdir $1
  mv ${GIT_PROJECT} ./$1
}

git_tag() {
  REF_KEY="git_tag"
  echo ${JIANMU_REF} > /tmp/ref
  REF_VALUE=`cut /tmp/ref -d "/" -f 3`
  git_init
  if [ ${JIANMU_DEPTH} -lt 1 ]; then
    git fetch origin ${JIANMU_REF}
  else
    git fetch --depth=${JIANMU_DEPTH} origin ${JIANMU_REF}
  fi
  git checkout -qf FETCH_HEAD

  COMMIT_ID=`git rev-parse HEAD`
  SHORT_COMMIT_ID=`git rev-parse --short HEAD`
  COMMIT_TIME=`git log --pretty=format:"%ad" --date=format:'%Y%m%d%H%M%S' | head -1`
  change_project_dir ${COMMIT_ID}

echo -e "{
     "\"git_path\"" ":" "\"${JM_SHARE_DIR}/${COMMIT_ID}/${GIT_PROJECT}\""","
     "\"${REF_KEY}\"" ":" "\"${REF_VALUE}\""","
     "\"commit_id\"" ":" "\"${COMMIT_ID}\""","
     "\"short_commit_id\"" ":" "\"${SHORT_COMMIT_ID}\""","
     "\"commit_time\"" ":" "\"${COMMIT_TIME}\""
}" > resultFile
}

git_branch() {
  REF_KEY="git_branch"
  echo ${JIANMU_REF} > /tmp/ref
  CHECKOUT_BRANCH=`cut /tmp/ref -d "/" -f 3`
  # exist commit id
  echo "clone"
  if [ -n "${JIANMU_COMMIT_ID}" ]; then
    git_init
    git fetch origin ${JIANMU_REF}
    git checkout ${JIANMU_COMMIT_ID} -b ${CHECKOUT_BRANCH}
  else
    # not exist commit id
    git_init
    if [ ${JIANMU_DEPTH} -lt 1 ]; then
      git fetch -vvv origin ${JIANMU_REF}
    else
      git fetch -vvv --depth=${JIANMU_DEPTH} origin ${JIANMU_REF}
    fi
    git checkout FETCH_HEAD
  fi

  COMMIT_ID=`git rev-parse HEAD`
  SHORT_COMMIT_ID=`git rev-parse --short HEAD`
  COMMIT_TIME=`git log --pretty=format:"%ad" --date=format:'%Y%m%d%H%M%S' | head -1`
  change_project_dir ${COMMIT_ID}

echo -e "{
     "\"git_path\"" ":" "\"${JM_SHARE_DIR}/${COMMIT_ID}/${GIT_PROJECT}\""","
     "\"${REF_KEY}\"" ":" "\"${CHECKOUT_BRANCH}\""","
     "\"commit_id\"" ":" "\"${COMMIT_ID}\""","
     "\"short_commit_id\"" ":" "\"${SHORT_COMMIT_ID}\""","
     "\"commit_time\"" ":" "\"${COMMIT_TIME}\""
}" > resultFile
}

git_pr() {
  git_init
  if [ -n "${JIANMU_COMMIT_ID}" ]; then
    # exist pr commit id
    git fetch origin ${JIANMU_REF}
    git checkout ${JIANMU_COMMIT_ID}
  else
    # not exist pr commit id
    if [ ${JIANMU_DEPTH} -lt 1 ]; then
      git fetch origin ${JIANMU_REF}
    else
      git fetch --depth=${JIANMU_DEPTH} origin ${JIANMU_REF}
    fi
    git checkout FETCH_HEAD
  fi

  COMMIT_ID=`git rev-parse HEAD`
  SHORT_COMMIT_ID=`git rev-parse --short HEAD`
  COMMIT_TIME=`git log --pretty=format:"%ad" --date=format:'%Y%m%d%H%M%S' | head -1`
  change_project_dir ${COMMIT_ID}

echo -e "{
     "\"git_path\"" ":" "\"${JM_SHARE_DIR}/${COMMIT_ID}/${GIT_PROJECT}\""","
     "\"commit_id\"" ":" "\"${COMMIT_ID}\""","
     "\"short_commit_id\"" ":" "\"${SHORT_COMMIT_ID}\""","
     "\"commit_time\"" ":" "\"${COMMIT_TIME}\""
}" > resultFile
}

case ${JIANMU_REF} in
  refs/tags/*  ) git_tag ;;
  refs/heads/* ) git_branch ;;
             * ) git_pr ;;
esac

mv ${COMMIT_ID} ${JM_SHARE_DIR}
  echo "resultFile:"
cat /usr/resultFile
